#include <iostream>
#include <queue>
#include <unordered_map>

using namespace std;
unordered_map<string, int> mp;
string aim;
string s;
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
 
void bfs()
{
	queue<string> q;
	q.push(s);
	mp[s] = 0;
	while(q.size())
	{
		auto t = q.front(); q.pop();
		
		int pos = 0;
		while(t[pos] != '0') pos++;
		int x = pos / 3;
		int y = pos % 3;
		for(int k = 0; k < 4; k++)
		{
			int i = x + dx[k];
			int j = y + dy[k];
			if(i >= 0 && j >= 0 && i <= 2 && j <= 2)
			{
				string tmp = t;
				swap(tmp[pos], tmp[i * 3 + j]);
				if(mp.count(tmp)) continue;
				mp[tmp] = mp[t] + 1;
				q.push(tmp);
				if(tmp == aim) return;
			}
		}
	}
}

int main()
{
	cin >> s;
	aim = "123804765";
	
	bfs();
	
	cout << mp[aim] << endl;
	
	return 0;
}
